<template>
    <div>
        <div class="hideMarker">
            <JNPFMarker :markerStyle="item.markerStyle" :ref="item.id" v-for="item in markerList" :key="item.id"
                :columnData="columnData" :text="item.text" />
        </div>

    </div>


</template>

<script>
import JNPFMarker from './jnpfMarker'
import html2canvas from 'html2canvas'
export default {
    components: {
        JNPFMarker
        // ContextMenuCom
    },
    props: {
        columnData: {
            type: Object,
            default: {}
        },
        activeMenu: {
            type: Object,
            default: {}
        },
        list: {
            type: Array,
            default: []
        },
        xbsjEarthUi: {
            type: Object
        }
    },
    data() {
        return {
            imgSource: {},
            markerList: [],
            moduleId: '',
            sceneObjects: [],//记录标注对象，方便管理
            infoWindow: undefined,
        }
    },
    watch: {
        list: {
            handler: function () {
                this.moduleId = this.activeMenu.moduleId
                this.initData()
            },
            deep: true,
        }
    },
    beforeUnmount() {
        this.clearObjects()
    },
    mounted() {

        // this.clearObjects()
        this.xbsjEarthUi.activeViewer.pickedEvent.don(e => {
            if(e.childPickedInfo.attachedInfo.pointerEvent.type!="pointerdown") return
            //点击其他位置关闭信息窗口，需厂家更新
            if (this.infoWindow) this.destroyInfoWindow()
        })
    },
    methods: {
        async initData() {
            let mapOptions = this.columnData.mapOptions //地图信息配置
            let markerStyle = this.columnData.markerStyle //标注风格
            let mapColorPlan = this.columnData.mapColorPlan //颜色方案
            if (mapOptions.useColorRules) this.$emit('updateColorPlan', { activeMenu: this.activeMenu, mapColorPlan: mapColorPlan, mapOptions: mapOptions })

            this.markerList = []
            if (mapOptions.innerType != "field") {
                this.markerList.push(
                    {
                        id: 'backgroundColor',
                        markerStyle: markerStyle,
                        text: '',
                    }
                )
                if (mapOptions.useColorRules) {
                    mapColorPlan.map(item => {
                        this.markerList.push(
                            {
                                id: item.id,
                                markerStyle: { ...markerStyle, backgroundColor: item.backgroundColor },
                                text: '',
                            }
                        )
                    })
                }
            } else {
                this.list.map(element => {
                    let value = element[mapOptions.compareField]
                    if (mapOptions.useColorRules) {
                        mapColorPlan.map(item => {
                            if (this.markerList.find(marker => marker.text == value)) return
                            if (mapOptions.compareType == 1) {
                                if (item.max >= Number(value) && Number(value) > item.min) {
                                    this.markerList.push(
                                        {
                                            id: item.id,
                                            markerStyle: { ...markerStyle, backgroundColor: item.backgroundColor },
                                            text: value,
                                        }
                                    )
                                }
                            }
                            if (mapOptions.compareType == 2) {
                                console.log(item.value, value)
                                if (item.value == value) {
                                    this.markerList.push(
                                        {
                                            id: item.id,
                                            markerStyle: { ...markerStyle, backgroundColor: item.backgroundColor },
                                            text: value,
                                        }
                                    )
                                }
                            }


                        })
                    }
                    if (this.markerList.find(marker => marker.text == value)) return
                    this.markerList.push(
                        {
                            id: 'backgroundColor-'+element.id,
                            markerStyle: { ...markerStyle },
                            text: value,
                        }
                    )

                })
                console.log('markerList', mapColorPlan, this.markerList)


            }
            await this.$nextTick(async () => {
                await this.dom2img()
                this.createSceneObject(this.moduleId)

            })

        },
        async dom2img() {
            // return
            if (!this.xbsjEarthUi.ueIsShow) return
            for (let i = 0; i < this.markerList.length; i++) {
                let tags = ['HEAD', 'LINK', 'STYLE']

                let markerDom = this.$refs[this.markerList[i].id][0].$el
                let canvas = await html2canvas(markerDom, {
                    backgroundColor: 'transparent', scale: 2, ignoreElements: (element) => {
                        if (element.compareDocumentPosition(markerDom) == 20 || element.getAttribute('name') == 'markerDom' || tags.indexOf(element.tagName) != -1) {
                            return false
                        } else {
                            return true
                        }

                    }
                })

                var imgData = canvas.toDataURL('image/png',1); // 将生成的canvas转换为DataURL格式
                this.markerList[i].$imgData = imgData
                console.log(11111, markerDom, imgData)

            }
        },
        clearObjects() {
            this.sceneObjects.map(obj => {
                this.xbsjEarthUi.destroySceneObject(obj)
            })
            this.infoWindow && this.destroyInfoWindow()
            this.sceneObjects = []

        },
        destroyInfoWindow() {
            this.xbsjEarthUi.destroySceneObject(this.infoWindow)
            this.infoWindow = undefined
        },
        createInfoWindow(point) {
            console.log(point)
            if (this.infoWindow) this.destroyInfoWindow()
            let xbsjEarthUi = this.xbsjEarthUi
            let info = this.xbsjEarthUi.createSceneObject('ESGeoDiv')
            info.position = point.position
            info.anchor = [0.5, 1.1]
            let _this = this

            // //复杂div设置
            class MyDiv {
                // container是Poi的div
                // eSGeoDiv指向当前的GeoCustomDivPoi场景对象
                // viewer指定当前的视口
                constructor(container, eSGeoDiv, viewer) {
                    this._container = container;
                    this._eSGeoDiv = eSGeoDiv
                    this._viewer = viewer
                    this._div = document.createElement('div');
                    this._container.appendChild(this._div);
                    this._div.className = `infoBox`;
                    this._div.style.width = xbsjEarthUi.infoWidth + 'px'
                    this._div.style.height = xbsjEarthUi.infoHeight + 'px'
                    this._divTitle = document.createElement('div');
                    this._divTitle.className = `infoBox-title`;
                    this._divTitle.innerHTML = `<div>${point.title}</div>`
                    this._divClose = document.createElement('div');
                    this._divClose.className = `infoBox-title-close`;
                    this._divClose.innerHTML = ` <span class="el-icon-close" ></span>`
                    this._divClose.addEventListener('click', () => { this.close(eSGeoDiv) })
                    this._divTitle.appendChild(this._divClose);
                    this._div.appendChild(this._divTitle);
                    this._divContent = document.createElement('div');
                    this._divContent.className = `infoBox-content`;
                    let contentHtml = ''
                    let videoMonitorInfo = []
                    point.subContent.map(sub => {
                        if (sub.jnpfKey == 'videoMonitor') {
                            // contentHtml+=`<div id='player'></div>`
                            videoMonitorInfo = sub.value ? JSON.parse(sub.value) : []
                            console.log('videoMonitorInfo', videoMonitorInfo)
                            if (videoMonitorInfo.length == 0) return
                            // point.videoiframeLinkurl = 'http://www.sinobroad.com:48080/#/play/wasm/ws%3A%2F%2F192.168.100.134%3A80%2Frtp%2F41010500002000000001_34020000001320000001.live.flv'
                            this._videoIframe = document.createElement('div');
                            this._videoIframe.className = `infoBox-iframe isCesium`;
                            // this._videoIframe.innerHTML = `<iframe src="http://127.0.0.1:8080${videoMonitorInfo[1]}?type=iframe" class='infoBox-iframe-body' scrolling='yes'/>`
                            this._videoIframe.innerHTML = `<div id='videoMonitor' class='infoBox-iframe-body'></div>`
                            this._div.appendChild(this._videoIframe);
                            // this._videoBtn = document.createElement('div');
                            // this._videoBtn.className = `infoBox-iframe-btn`;
                            // this._videoBtn.innerHTML = `查看`
                            // this._videoBtn.addEventListener('click', function () {
                            //     window.open(`http://127.0.0.1:8080${videoMonitorInfo[1]}`)
                            // })
                            // this._div.appendChild(this._videoBtn);
                            _this.$nextTick(() => {
                                this.create()
                                this.play(`${videoMonitorInfo[1]}`)
                            })

                            // console.log('videoMonitorInfo',videoMonitorInfo)

                        } else {
                            contentHtml += `<div>${sub.label}:${sub.value}</div>`
                        }
                    })
                    this._divContent.innerHTML = contentHtml
                    if (contentHtml) this._div.appendChild(this._divContent);


                    if (point.iframeLinkurl) {
                        this._divIframe = document.createElement('div');
                        this._divIframe.className = `infoBox-iframe`;
                        this._divIframe.innerHTML = `<iframe src=${point.iframeLinkurl} class='infoBox-iframe-body' scrolling='yes'/>`
                        this._div.appendChild(this._divIframe);

                    }
                }
                create(options) {
                    this.jessibuca = new window.Jessibuca(
                        {
                            container: document.getElementById('videoMonitor'),
                            decoder: "jessibuca/decoder.js",
                            isResize: false,
                            text: "",
                            // background: "bg.jpg",
                            loadingText: "疯狂加载中...",
                            debug: true,
                            supportDblclickFullscreen: true,
                            showBandwidth: true, // 显示网速
                            operateBtns: {
                                fullscreen: true,
                                screenshot: true,
                                play: true,
                                audio: true,
                            },
                            forceNoOffscreen: true,
                            isNotMute: true,
                            timeout: 10
                        }
                    );
                    var _this = this;
                    this.jessibuca.on("load", function () {
                        console.log("on load");
                    });

                    this.jessibuca.on("log", function (msg) {
                        console.log("on log", msg);
                    });
                    this.jessibuca.on("record", function (msg) {
                        console.log("on record:", msg);
                    });
                    this.jessibuca.on("pause", function () {
                        console.log("on pause");
                        _this.playing = false;
                    });
                    this.jessibuca.on("play", function () {
                        console.log("on play");
                        _this.playing = true;
                    });
                    this.jessibuca.on("fullscreen", function (msg) {
                        console.log("on fullscreen", msg);
                    });

                    this.jessibuca.on("mute", function (msg) {
                        console.log("on mute", msg);
                        _this.quieting = msg;
                    });

                    this.jessibuca.on("mute", function (msg) {
                        console.log("on mute2", msg);
                    });

                    this.jessibuca.on("audioInfo", function (msg) {
                        console.log("audioInfo", msg);
                    });

                    // this.jessibuca.on("bps", function (bps) {
                    //   // console.log('bps', bps);
                    // });
                    // let _ts = 0;
                    // this.jessibuca.on("timeUpdate", function (ts) {
                    //     console.log('timeUpdate,old,new,timestamp', _ts, ts, ts - _ts);
                    //     _ts = ts;
                    // });

                    this.jessibuca.on("videoInfo", function (info) {
                        console.log("videoInfo", info);
                    });

                    this.jessibuca.on("error", function (error) {
                        console.log("error", error);
                    });

                    this.jessibuca.on("timeout", function () {
                        console.log("timeout");
                    });

                    this.jessibuca.on('start', function () {
                        console.log('frame start');
                    })

                    this.jessibuca.on("performance", function (performance) {
                        var show = "卡顿";
                        if (performance === 2) {
                            show = "非常流畅";
                        } else if (performance === 1) {
                            show = "流畅";
                        }
                        _this.performance = show;
                    });
                    this.jessibuca.on('buffer', function (buffer) {
                        console.log('buffer', buffer);
                    })

                    this.jessibuca.on('stats', function (stats) {
                        console.log('stats', stats);
                    })

                    this.jessibuca.on('kBps', function (kBps) {
                        console.log('kBps', kBps);
                    });

                    this.jessibuca.on("play", () => {
                        this.playing = true;
                        this.loaded = true;
                        this.quieting = this.jessibuca.isMute();
                    });

                    this.jessibuca.on('recordingTimestamp', (ts) => {
                        console.log('recordingTimestamp', ts);
                    })


                    // console.log(this.jessibuca);
                }
                play(playUrl) {
                    if (playUrl) {
                        console.log(playUrl)
                        this.jessibuca.play(playUrl);
                    }
                }
                close(eSGeoDiv) {
                    console.log(this)
                    this.jessibuca && this.jessibuca.destroy()
                    if (_this.infoWindow) _this.destroyInfoWindow()
                }
                // 销毁函数，注意此函数必需，否则会报错！
                destroy() {
                    console.log('销毁窗口')
                    this.jessibuca && this.jessibuca.destroy()
                    // this._container.removeChild(this._div);
                }
            }
            info.instanceClass = MyDiv;

            // let renderHtml =
            //     `<div class="infoBox">
            //         <div class="infoBox-title">
            //             <div>${point.title}</div>
            //             <div class="infoBox-title-close" onclick="destroyInfoWindow()" >
            //                 <span class="el-icon-close" ></span>
            //             </div>
            //         </div>
            //         <div class="infoBox-content">`
            // point.subContent.map(sub=>{
            //     renderHtml+=`<div>${sub.label}:${sub.value}</div>`
            // })
            // renderHtml+=  `</div></div>`
            // info.innerHTML = renderHtml
            info.pickedEvent.don(e => {
                info.editing = false
            })
            this.infoWindow = info


            // info.show = false
        },
        getImgData(element) {
            let mapOptions = this.columnData.mapOptions //地图信息配置
            let mapColorPlan = this.columnData.mapColorPlan //颜色方案
            let id = ''
            if (mapOptions.useColorRules) {
                mapColorPlan.map(item => {
                    let value = element[mapOptions.compareField]
                    if (mapOptions.compareType == 1) {
                        if (item.max >= Number(value) && Number(value) > item.min) {
                            id = item.id
                        }
                    }
                    if (mapOptions.compareType == 2) {
                        if (item.value == value) {
                            id = item.id
                        }
                    }
                })
            }
            if(!id){
                if (mapOptions.innerType != "field") {
                    id = 'backgroundColor'
                }else{
                    id = 'backgroundColor-'+element.id
                }
                
            }
            
            
            let obj = this.markerList.find(item => item.id == id) || undefined
            return obj
        },
        createSceneObject(id) {
            this.clearObjects()
            let mapOptions = this.columnData.mapOptions //地图信息配置
            let markerStyle = this.columnData.markerStyle //标注风格
            let mapColorPlan = this.columnData.mapColorPlan //颜色方案
            let minLon = Infinity
            let maxLon = -Infinity
            let minLat = Infinity
            let maxLat = -Infinity

            this.list.forEach(element => {
                if (!element[mapOptions.lnglat]) return
                let position = []
                try {
                    position = [...JSON.parse(element[mapOptions.lnglat])]
                } catch (e) {
                    return
                    console.log(e)
                }

                if (position.length == 2) position.push(0)
                position = position.map(Number)
                // console.log('position',position)
                minLon = Math.min(minLon, position[0])
                maxLon = Math.max(maxLon, position[0])
                minLat = Math.min(minLat, position[1])
                maxLat = Math.max(maxLat, position[1])

                let ESOBJ = 'ESGeoDiv'
                let pointText = undefined

                //ueIsShow
                if (this.xbsjEarthUi.ueIsShow) {
                    ESOBJ = 'ESImageLabel'
                    pointText = this.xbsjEarthUi.createSceneObject('ESTextLabel')
                    pointText.position = position
                    pointText.text = element[mapOptions.title]
                    pointText.fontSize = 12
                    pointText.padding = [5,5,5,5]
                    pointText.anchor = [0.5,0]
                } 
                let point = this.xbsjEarthUi.createSceneObject(ESOBJ)
               
                point.moduleId = id
                point.dataId = element.id
                point.iframeLinkurl = element['Iframe_Linkurl'] ? element['Iframe_Linkurl'] + '?dataId=' + element.id : ''
                point.iframeLinkurl = point.iframeLinkurl.replace(/\${tb}/g, localStorage.getItem('jnpf_tburl')).replace(/\${tbToken}/g, localStorage.getItem('jnpf_tbtoken')).replace(/\${tbRefreshToken}/g, localStorage.getItem('jnpf_tbrefreshtoken'))
                point.position = position
                point.anchor = [0.5,1.2]
               

                let subContent = []
                if (this.columnData.mapSubTitles && this.columnData.mapSubTitles.length > 0) {
                    this.columnData.mapSubTitles.map(subtitle => {
                        let columnInfo = this.columnData.columnList.find(item => { return item.prop == subtitle.value })
                        // console.log(columnInfo)
                        subContent.push({
                            jnpfKey: columnInfo.jnpfKey,
                            key: subtitle.value,
                            label: (columnInfo && columnInfo.label) || '-',
                            value: element[subtitle.value]
                        })
                    })
                }
                point.title = element[mapOptions.title]
                point.subContent = subContent

                let backgroundColor = markerStyle.backgroundColor

                if (mapOptions.useColorRules) {
                    this.$emit('updateColorPlan', { activeMenu: this.activeMenu, mapColorPlan: mapColorPlan, mapOptions: mapOptions })
                    mapColorPlan.map(item => {
                        // if(eval(Number(element[mapOptions.compareField])+item.compare+item.value)){
                        //     backgroundColor = item.backgroundColor
                        // }
                        let value = element[mapOptions.compareField]
                        if (mapOptions.compareType == 1) {
                            if (item.max >= Number(value) && Number(value) > item.min) {
                                backgroundColor = item.backgroundColor
                            }
                        }
                        if (mapOptions.compareType == 2) {
                            if (item.value == value) {
                                backgroundColor = item.backgroundColor
                            }
                        }
                    })
                }

                let renderHtml =
                    ` 
                    <div class="marker">
                        <div class="markerStyle">
                            <div class="markerStyle-bg">
                                <div class="markerStyle-circle"  style="background: ${backgroundColor}"></div>
                                <div class="markerStyle-rect" style="background: ${backgroundColor}"></div>
                            </div>
                            <div class="markerStyle-icon"  style="color:${markerStyle.textColor}">`
                if (mapOptions.innerType == "field") {
                    renderHtml += element[mapOptions.innerField]
                } else {
                    renderHtml += `<i class="${markerStyle.icon}"></i>`
                }
                renderHtml +=
                    `</div>
                        </div>
                        <div class="markerStyle-text" title='${point.title}'>${point.title}</div>
                    </div>
                    `
                
                // point.innerHTML = renderHtml

                if (this.xbsjEarthUi.ueIsShow) {
                    let marker = this.getImgData(element)
                    point.url = marker ? marker.$imgData : ''
                    point.sizeByContent = false
                    point.size = [36, 44]
                }
                else{
                    point.innerHTML = renderHtml
                }
              
                point.allowPicking = true
                // point.editing = false

                var that = this
               
                point.widgetEvent.don(e => {
                    if(e.type !== "leftClick") return
                    console.log(e)
                    // that.$emit('updateActivePoint', point)
                    // return
                    // point.editing = false
                    // point.flyTo()

                    that.$emit('updateActivePoint', point)//都在页面中间显示
                    // if (this.xbsjEarthUi.ueIsShow) {
                    //     that.$emit('updateActivePoint', point)
                    // } else {
                    //     that.createInfoWindow(point)
                    // }
                    // point.scale = [2,2,2]
                    let data = {
                        type: 'clickPoint',
                        pointInfo: {
                            moduleId: point.moduleId,
                            dataId: point.dataId
                        }
                    }
                    // window.top.postMessage(JSON.stringify(data), '*')
                    //点击飞入到当前点位，需厂家更新
                    // that.createInfoWindow(point) 
                   
                })
                this.sceneObjects.push(point)
                // ueIsShow
                if (this.xbsjEarthUi.ueIsShow) {
                    this.sceneObjects.push(pointText)
                }
            })

            if (minLon != Infinity && maxLon != -Infinity && minLat != Infinity && maxLat != -Infinity) {
                let rectangle = Cesium.Rectangle.fromDegrees(minLon, minLat, maxLon, maxLat)
                console.log(rectangle)
                if (this.xbsjEarthUi.cameraViewsManager.views.length > 0) return
                // this.xbsjEarthUi.activeViewer.flyIn([(minLon+maxLon)/2,(minLat+maxLat)/2,5000])
                this.xbsjEarthUi.activeViewer.innerViewer.viewer.camera.flyTo({
                    destination: rectangle,
                    duration: 1
                })
            }



        },

    },
}
</script>
<style>
.hideMarker {
    position: fixed;
    width: 100%;
    left: 10px;
    /* top: 10px;
    z-index: 99999; */
}

.marker {
    display: flex;
    flex-direction: column;
    position: relative;
}
.marker:hover{
    cursor:pointer;
}

.markerStyle-text {
    position: absolute;
    top: 48px;
    background: rgba(0, 0, 0, .7);
    color: #fff;
    line-height: 1.5em;
    font-size: 13px;
    white-space: nowrap;
    left: 50%;
    transform: translate(-50%);
    border-radius: 5px;
    padding: 0 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 180px;
}

.markerStyle {
    width: 36px;
    height: 44px;
    position: relative;
}

.markerStyle-bg {
    background: transparent;
    transform: rotate(45deg);
    width: 36px;
    height: 36px;
}

.markerStyle-icon {
    position: absolute;
    color: #fff;
    left: 50%;
    width: 100%;
    line-height: 38px;
    top: 0;
    transform: translate(-50%);
    font-size: 12px;
    text-align: center;
    /* overflow: hidden;
    white-space: nowrap;
    text-align: center; */
}

.markerStyle-circle {
    position: absolute;
    left: 0;
    top: 0;
    border-radius: 100%;
    width: 32px;
    height: 32px;
    border: 2px solid rgba(255, 255, 255, 1);
}

.markerStyle-rect {
    position: absolute;
    left: 16px;
    top: 16px;
    width: 18px;
    height: 18px;
    border-bottom: 2px solid rgba(255, 255, 255, 1);
    border-right: 2px solid rgba(255, 255, 255, 1);
}
</style>